package com.sun.controller;


import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.common.QueryPageParam;
import com.sun.common.Result;
import com.sun.common.UploadDataListener;
import com.sun.deploy.net.URLEncoder;
import com.sun.entity.*;
import com.sun.mapper.GoodsMapper;
import com.sun.mapper.GoodstypeMapper;
import com.sun.mapper.StorageMapper;
import com.sun.mapper.UserMapper;
import com.sun.service.GoodsService;
import com.sun.service.LogisticsService;
import com.sun.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器：物品管理
 * </p>
 *
 * @author rabbiter
 * @since 2023-01-06
 */
@RestController
@RequestMapping("/logistics")
public class LogisticsController {

    @Autowired
    private LogisticsService logisticsService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private StorageMapper storageMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private GoodstypeMapper goodstypeMapper;
    /*
     * 新增物品
     * @author rabbiter
     * @date 2023/1/6 12:12
     */
    @PostMapping("/save")
    public Result save(@RequestBody Goods goods) {
        return goodsService.save(goods) ? Result.success() : Result.fail();
    }

    /*
     * 更新物品
     * @author rabbiter
     * @date 2023/1/6 13:22
     */
    @PostMapping("/update")
    public Result update(@RequestBody Goods goods) {
        return goodsService.updateById(goods) ? Result.success() : Result.fail();
    }

    /*
     * 删除物品
     * @author rabbiter
     * @date 2023/1/6 13:24
     */
    @GetMapping("/del")
    public Result del(@RequestParam String id) {
        return goodsService.removeById(id) ? Result.success() : Result.fail();
    }

    /*
     * 模糊查询：根据输入查询物品并以分页的形式展示
     * @author rabbiter
     * @date 2023/1/6 13:31
     */
    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query, HttpSession session) {

        Page<Logistics> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());
        LambdaQueryWrapper<Logistics> queryWrapper = new LambdaQueryWrapper<>();

        //权限系统
        String json = (String) redisTemplate.opsForValue().get("user");
        User user = JSONUtil.toBean(json, User.class);
        if (user.getRoleId()==2){
            queryWrapper.eq(Logistics::getSender,user.getName()).or().eq(Logistics::getReceiver,user.getName());
        }
        IPage result = logisticsService.pageCC(page, queryWrapper);
        List<Logistics> records = result.getRecords();
        return Result.success(records, result.getTotal());
    }

    @GetMapping("/not")
    public Result not(@RequestParam("id") java.lang.String id) {
        Logistics logistics = new Logistics();
        logistics.setId(id);
        logistics.setLogisticsStatus("已取消");
        return logisticsService.updateById(logistics) ? Result.success() : Result.fail();
    }

    @GetMapping("/isok")
    public Result isok(@RequestParam("id") java.lang.String id) {
        Logistics logistics = new Logistics();
        logistics.setId(id);
        logistics = logisticsService.getById(id);
        logistics.setLogisticsStatus("运输中");

        Record record = new Record();
        record.setGoods(goodsMapper.getIdBynameAndCell(logistics.getName(),logistics.getOutput()));
        record.setUserid(userMapper.getIdByName(logistics.getSender()));
        record.setAdminId(userMapper.getIdByName(logistics.getSender()));
        record.setCount(logistics.getCount());
        record.setCell(logistics.getOutput());
        record.setRemark("出库到"+logistics.getInput());
        record.setAction("2");
        this.save22(record);

        //入库
        //判断有无该物品
        //有进行修改
        Goods goodByNameAndCell = goodsMapper.getGoodByNameAndCell(logistics.getName(), logistics.getInput());
        if (goodByNameAndCell!=null){
            Record record2 = new Record();
            record2.setGoods(goodByNameAndCell.getId());
            record2.setUserid(userMapper.getIdByName(logistics.getSender()));
            record2.setAdminId(userMapper.getIdByName(logistics.getSender()));
            record2.setCount(logistics.getCount());
            record2.setCell(logistics.getOutput());
            record2.setRemark("入库");
            this.save22(record2);
        } else {
            Goods goods2 = new Goods();
            goods2.setName(logistics.getName());
            goods2.setCell(logistics.getInput());
            Integer cellIdByCellNameAndType = storageMapper.getCellIdByCellNameAndType(logistics.getInput(), logistics.getStorageType());
            goods2.setStorage(String.valueOf(cellIdByCellNameAndType));
            goods2.setCount(logistics.getCount());
            Integer idByName = goodstypeMapper.getIdByName(logistics.getGoodType());
            goods2.setGoodstype(String.valueOf(idByName));
            goodsMapper.insert(goods2);

            goodByNameAndCell = goodsMapper.getGoodByNameAndCell(logistics.getName(), logistics.getOutput());
            Record record2 = new Record();
            record2.setGoods(goodByNameAndCell.getId());
            record2.setUserid(userMapper.getIdByName(logistics.getSender()));
            record2.setAdminId(userMapper.getIdByName(logistics.getSender()));
            record2.setCount(logistics.getCount());
            record2.setCell(logistics.getOutput());
            record2.setRemark("入库");
            this.save23(record2);
        }

        return logisticsService.updateById(logistics) ? Result.success() : Result.fail();
    }
    public void save22(@RequestBody Record record) {

        //权限系统
        String json = (String) redisTemplate.opsForValue().get("user");
        User user = JSONUtil.toBean(json, User.class);

        Goods goods = goodsService.getById(record.getGoods());
        int n = record.getCount();
        // 出库
        if ("2".equals(record.getAction())) {
            n = -n;
            record.setCount(n);
        }
        int num = goods.getCount() + n;
        if (num < 0) {
        }
        goods.setCount(num);
        goodsService.updateById(goods);
        record.setCreatetime(LocalDateTime.now());
        record.setCell(goods.getCell());
        record.setUserid(user.getId());
        recordService.save(record);
    }


    public void save23(@RequestBody Record record) {

        //权限系统
        String json = (String) redisTemplate.opsForValue().get("user");
        User user = JSONUtil.toBean(json, User.class);

        Goods goods = goodsService.getById(record.getGoods());
        int n = record.getCount();
        // 出库
        if ("2".equals(record.getAction())) {
            n = -n;
            record.setCount(n);
        }
        int num = goods.getCount() + n;
        if (num < 0) {
        }
        goods.setCount(num);
//        goodsService.updateById(goods);
        record.setCreatetime(LocalDateTime.now());
        record.setCell(goods.getCell());
        record.setUserid(user.getId());
        recordService.save(record);
    }


    @GetMapping("/notok")
    public Result notok(@RequestParam("id") java.lang.String id) {
        Logistics logistics = new Logistics();
        logistics.setId(id);
        logistics.setLogisticsStatus("未通过");
        return logisticsService.updateById(logistics) ? Result.success() : Result.fail();
    }

    @GetMapping("/okok")
    public Result okok(@RequestParam("id") java.lang.String id) {
        Logistics logistics = new Logistics();
        logistics.setId(id);
        logistics.setLogisticsStatus("已收货");
        return logisticsService.updateById(logistics) ? Result.success() : Result.fail();
    }


    @GetMapping("/download")
    public void downloadFile(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 假设你已经有了一个名为goodsList的List<Goods>对象
        List<Goods> goodsList = goodsService.getMuban();

//        select * from  storage where  id =1


        for (Goods goods : goodsList) {
            Storage storageById = goodsService.getStorageById(goods.getStorage());
            goods.setStorage(storageById.getName());
            goods.setCell(storageById.getCell());
            Goodstype goodstype = goodsService.getGoodstype(goods.getGoodstype());
            goods.setGoodstype(goodstype.getName());
        }

        // 使用EasyExcel的write()方法将数据写入到OutputStream中
        // 这将创建一个新的Excel表格，使用Goods类的字段作为列标题，goodsList中的每个元素作为新的行
        EasyExcel.write(response.getOutputStream(), Goods.class).sheet("模板").doWrite(goodsList);
    }

    @PostMapping("/upload")
    @ResponseBody
    public Result upload(MultipartFile file) throws IOException {
        UploadDataListener listener = new UploadDataListener(goodsMapper);
        EasyExcel.read(file.getInputStream(), Goods.class, listener).sheet().doRead();
        List<Goods> goodsList = listener.getGoodsList();
        for (Goods goods : goodsList) {
            Integer id = goods.getId();
            Integer count = goods.getCount();
            if (count != null && count != 0) {
                Record record = new Record();
                record.setCount(count);
                record.setGoods(id);
                if (count > 0) {
                    record.setRemark("入库");
                } else {
                    record.setRemark("出库");
                }
                String json = (String) redisTemplate.opsForValue().get("user");
                User user1 = JSONUtil.toBean(json, User.class);
                Integer id1 = user1.getId();
                record.setAdminId(id1);

                record.setAction("1");
                record.setUserid(3);
                save(record);
            }
        }
        return Result.success();
    }

    public void save(Record record) {
        Goods goods = goodsService.getById(record.getGoods());
        int n = record.getCount();
        // 出库
        if ("2".equals(record.getAction())) {
            n = -n;
            record.setCount(n);
        }

        int num = goods.getCount() + n;
        if (num < 0) {
            return;
        }
        goods.setCount(num);
        goodsService.updateById(goods);
        record.setCreatetime(LocalDateTime.now());
        recordService.save(record);
    }


}
